package net.begincode.searchCommon.util;

import net.begincode.searchCommon.bean.Page;
import net.begincode.searchCommon.bean.searchResult;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hlj~宇晗
 * @create 2017-03-27 10:44
 **/
public class JSONUtil {
	//设置数据data
	public static Page setAllParam(HttpEntity httpEntity){
		Page page=new Page();
		try {
			JSONObject jsonObject =
					new JSONObject(EntityUtils.toString(httpEntity,"UTF-8"));
			List<searchResult> results=new ArrayList<>();

			//设置总页数
			Integer totalPage=
					jsonObject.getJSONObject("cursor").getJSONArray("pages").length();
			page.setTotalPage(totalPage);
			//设置总结果数
			Integer totalNum=
					Integer.parseInt(jsonObject.getJSONObject("cursor").getString("resultCount"));
			page.setTotalNum(totalNum);

			//设置data数据
			JSONArray jsonArray = jsonObject.getJSONArray("results");
			for (int i = 0; i < jsonArray.length(); i++) {//遍历
				JSONObject jsonObject1 = (JSONObject) jsonArray.opt(i);
				searchResult result = new searchResult();
				//仅仅截取
				result.setTitle(jsonObject1.getString("title"));
				result.setContent(jsonObject1.getString("content"));
				result.setUrl(jsonObject1.getString("url"));
				results.add(result);
			}
			page.setData(results);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return page;
	}
}
